package com.hiss.basic.starter.websocket.handler;

import com.hiss.basic.starter.websocket.manager.WebSocketSessionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Objects;

@Slf4j
public class WebSocketHandler extends TextWebSocketHandler {

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String principal = Objects.requireNonNull(session.getPrincipal()).getName();
        log.info("WebSocket 连接建立: principal={}", principal);
        WebSocketSessionManager.open(session);
        super.afterConnectionEstablished(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String principal = Objects.requireNonNull(session.getPrincipal()).getName();
        log.info("WebSocket 连接关闭: principal={}", principal);
        WebSocketSessionManager.close(session);
        super.afterConnectionClosed(session, status);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        log.info("WebSocket 接收消息: message={}", message.getPayload());
        String payload = message.getPayload();
        if ("ping".equals(payload)) {
            session.sendMessage(new TextMessage("pong"));
        }
    }
}
